package com.example.springbootwebfluxdemo.util;

import org.springframework.web.reactive.function.server.ServerRequest;


public class RequestIpUtil {
	public static String getUserIp(ServerRequest request){
		final String ERROR_IP = "127.0.0.1";
		ServerRequest.Headers headers = request.headers();
		String ip = headers.firstHeader("X-Real-IP");

//		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip =  headers.firstHeader("x-forwarded-for");
		}
 
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
//			new String(request.remoteAddress().get().getAddress().getAddress())
//			ip = request.getRemoteAddr();
			ip = new String(request.remoteAddress().get().getAddress().getAddress());
			if ("0:0:0:0:0:0:0:1".equals(ip))
			{
				ip = ERROR_IP;
			}
		}
		if ("unknown".equalsIgnoreCase(ip))
		{
			ip = ERROR_IP;
			return ip;
		}
		int index = ip.indexOf(',');
		if (index >= 0)
		{
			ip = ip.substring(0, index);
		}
 
		return ip;
	}


//	public static String getRequestIp() {
//		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//		// 从获取RequestAttributes中获取HttpServletRequest的信息
//		HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
//		String ip = request.getHeader("x-forwarded-for");
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("Proxy-Client-IP");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("WL-Proxy-Client-IP");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("HTTP_CLIENT_IP");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
//		}
//		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
//			ip = request.getRemoteAddr();
//		}
//		return ip;
//	}

}